import { View } from '@tarojs/components'
import GlobalData from '../../../global'
import { uploadUserInfoApi } from '../../../services/User'
import { AtButton } from 'taro-ui'
import { useState } from 'react'
import Taro, { getApp, useReady } from '@tarojs/taro'
import { isWechat } from '../../../utils'
const CONFIG = require('../../../config')
const app = getApp()


export default () => {



    let [canIUseGetUserProfile, setcanIUseGetUserProfile] = useState(false)
    
    function uploadUserInfo(data) {
        const userInfo = data.userInfo
        Taro.showLoading()
        uploadUserInfoApi({
            nickname : userInfo.nickName,
            avatar : userInfo.avatarUrl,
            gender : userInfo.gender
        }).finally(() => {
            Taro.hideLoading()
            Taro.navigateBack()
        })

        app.$app.updateUserInfo(data.userInfo.nickName, data.userInfo.avatarUrl)
    }

    function getUserInfo(e:any) {
        if(canIUseGetUserProfile) {
            Taro.getUserProfile({
                desc : '获取用户信息',
                success(res){
                    uploadUserInfo(res)
                },
                fail(error) {
                  console.log(error)
                }
            })
        }else {
            uploadUserInfo(e.detail)
        }
        
    }


    useReady(() => {
        if(isWechat()) {
            if(typeof Taro.getUserProfile != 'undefined') { //判断有无getUserProfile方法
                setcanIUseGetUserProfile(true)
            }
        }
    })

    return <>
        <View className='fixed xy p-l-r w-100'>
            {canIUseGetUserProfile ? <AtButton type='primary' onClick={getUserInfo}>立即登录</AtButton> : <AtButton type='primary' openType='getUserInfo' onGetUserInfo={getUserInfo}>立即登录</AtButton> }
        </View>
    </>
}